<template>

<!--  <el-form :inline="true" :model="productQuery" :rules="productRules">

    <el-form-item label="产品名称">
      <el-input v-model="productQuery.name" placeholder="请输入产品名称" clearable />
    </el-form-item>

    <el-form-item label="交易阶段">
      <el-select
          v-model="productQuery.state"
          placeholder="请选择交易阶段"
          style="width: 200px"
          clearable>
        <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSearch">搜 索</el-button>
      <el-button type="primary" plain @click="onReset">重 置</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary" @click="add">新增产品</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>

  <el-table
      :data="productList"
      style="width: 100%"
      @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="55"/>
    <el-table-column type="index" label="序号" width="70"/>
    <el-table-column property="name" label="产品名称" width="120"/>
    <el-table-column property="guidePriceS" label="官方指导起始价" width="150" show-overflow-tooltip/>
    <el-table-column property="guidePriceE" label="官方指导最高价" width="150"/>
    <el-table-column property="quotation" label="经销商报价" width="100"/>
    <el-table-column property="state" label="状态" show-overflow-tooltip>
      <template #default="scope" >
        <span v-if="scope.row.state === 0">在售</span>
        <span v-else>售罄</span>
      </template>
    </el-table-column>
    <el-table-column property="createTime" label="创建时间" width="200"/>
    <el-table-column property="createByDO.name" label="创建人" show-overflow-tooltip/>
    <el-table-column property="editTime" label="编辑时间" width="200"/>
    <el-table-column property="editByDO.name" label="编辑人" />
    <el-table-column label="操作" width="230">
      <template #default="scope">
&lt;!&ndash;        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>&ndash;&gt;
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"/>

  &lt;!&ndash;  新增产品的弹窗（对话框）&ndash;&gt;
  <el-dialog v-model="productDialogVisible" :title="productQuery.id > 0 ? '编辑产品' : '新增产品'" center width="55%"
             draggable>
    <el-form ref="productRefFrom" :model="productQuery" label-width="130px" :rules="productRules">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="productQuery.name"/>
      </el-form-item>

      <el-form-item label="官方指导起始价" prop="guidePriceS">
        <el-input v-model="productQuery.guidePriceS"/>
      </el-form-item>

      <el-form-item label="官方指导最高价" prop="guidePriceE">
        <el-input v-model="productQuery.guidePriceE"/>
      </el-form-item>

      <el-form-item label="经销商报价" prop="quotation">
        <el-input v-model="productQuery.quotation"/>
      </el-form-item>

      <el-form-item label="产品状态" prop="state">
        <el-select
            v-model="productQuery.state"
            placeholder="请选择产品状态"
            style="width: 100%"
            clearable>
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>


    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="productDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="productSubmit">提 交</el-button>
      </div>
    </template>
  </el-dialog>-->


  <div class="form-container">
    <el-form :inline="true" :model="productQuery" :rules="productRules">

      <el-form-item label="产品名称">
        <el-input v-model="productQuery.name" placeholder="请输入产品名称" clearable />
      </el-form-item>

      <el-form-item label="交易阶段">
        <el-select
            v-model="productQuery.state"
            placeholder="请选择交易阶段"
            style="width: 200px"
            clearable>
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSearch">搜 索</el-button>
        <el-button type="primary" plain @click="onReset">重 置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="table-container">
    <el-button type="primary" @click="add">新增产品</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>

    <el-table
        :data="productList"
        style="width: 100%"
        @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" label="序号" width="70"/>
      <el-table-column property="name" label="产品名称" width="120"/>
      <el-table-column property="guidePriceS" label="官方指导起始价" width="150" show-overflow-tooltip/>
      <el-table-column property="guidePriceE" label="官方指导最高价" width="150"/>
      <el-table-column property="quotation" label="经销商报价" width="100"/>
      <el-table-column property="state" label="状态" show-overflow-tooltip>
        <template #default="scope" >
          <span v-if="scope.row.state === 0">在售</span>
          <span v-else>售罄</span>
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间" width="200"/>
      <el-table-column property="createByDO.name" label="创建人" show-overflow-tooltip/>
      <el-table-column property="editTime" label="编辑时间" width="200"/>
      <el-table-column property="editByDO.name" label="编辑人" />
      <el-table-column label="操作" width="230">
        <template #default="scope">
          <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
        @prev-click="toPage"
        @next-click="toPage"
        @current-change="toPage"/>
  </div>

  <!-- 新增产品的弹窗（对话框）-->
  <el-dialog v-model="productDialogVisible" :title="productQuery.id > 0 ? '编辑产品' : '新增产品'" center width="55%"
             draggable>
    <el-form ref="productRefFrom" :model="productQuery" label-width="130px" :rules="productRules">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="productQuery.name"/>
      </el-form-item>

      <el-form-item label="官方指导起始价" prop="guidePriceS">
        <el-input v-model="productQuery.guidePriceS"/>
      </el-form-item>

      <el-form-item label="官方指导最高价" prop="guidePriceE">
        <el-input v-model="productQuery.guidePriceE"/>
      </el-form-item>

      <el-form-item label="经销商报价" prop="quotation">
        <el-input v-model="productQuery.quotation"/>
      </el-form-item>

      <el-form-item label="产品状态" prop="state">
        <el-select
            v-model="productQuery.state"
            placeholder="请选择产品状态"
            style="width: 100%"
            clearable>
          <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="productDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="productSubmit">提 交</el-button>
      </div>
    </template>
  </el-dialog>



</template>

<script >
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "ProductDetailView",

  //注入
  inject: ['reload'],

  data() {
    return {
      productList: [{
        createByDO:{},
        editByDO:{},
        stateByDO:{},
      }], //产品列表
      pageSize: 0, //每页显示的条数
      total: 0, //总条数
      productIdArray: [], //勾选或者取消勾选的数据会传给我们这个函数

      //产品表单对象，初始值是空
      productQuery: {
        createByDO:{},
        editByDO:{}
      },
      //产品状态的下拉选项
      stateOptions: [
        {
          value: 0,
          label: '在售',
        },
        {
          value: 1,
          label: '售罄',
        },
      ],
      //定义录入表单验证规则
      productRules: {
        guidePriceS: [
          {required: true, message: '请输入官方指导起始价', trigger: 'blur'},
          {pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '官方指导起始价必须是正整数或两位小数', trigger: 'blur'},
        ],
        guidePriceE: [
          {required: true, message: '请输入官方指导最高价', trigger: 'blur'},
          {pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '官方指导最高价必须是正整数或两位小数', trigger: 'blur'},
        ],
        quotation: [
          {required: true, message: '请输入经销商报价', trigger: 'blur'},
          {pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '经销商报价必须是正整数或两位小数', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入产品名称', trigger: 'blur'},
        ],
        state: [
          {required: true, message: '请选择产品状态', trigger: 'blur'},
        ],
      },
      ////新增或编辑产品的弹窗是否显示
      productDialogVisible: false,

    }
  },

  mounted() {
    this.getData(1);
  },

  methods: {
    //勾选或者取消勾选时，触发该函数（已经勾选的数据会传给我们这个函数）
    handleSelectionChange(selectionDataArray) {
      this.productIdArray = [];//清空一下之前选中的数据，只需要最后一次的选中的数据
      selectionDataArray.forEach(data=>{
        let productId = data.id;
        this.productIdArray.push(productId);
      })
    },

    //查询产品列表
    getData(current) {
      doGet("/api/products", {
        current: current, //当前查询第几页
        //两个搜索条件参数
        name: this.productQuery.name, //产品名称
        state: this.productQuery.state,//产品状态
      }).then(resp => {
        if (resp.data.code === 200) {
          this.productList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      })
    },

    //分页函数（current是element-plus组件传过来，就是传的当前页）
    toPage(current) {
      this.getData(current);
    },

    //新增产品
    add() {
      this.productQuery = {};
      this.productDialogVisible = true;
    },

    //编辑产品
    edit(id) {
      this.productDialogVisible = true;
      this.loadProduct(id);
    },

    //加载要编辑的产品
    loadProduct(id) {
        doGet("/api/product/detail/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            this.productQuery = resp.data.data;
          }
        })
    },

    //新增产品提交保存
    productSubmit() {
      let formData = new FormData();
      for (let field in this.productQuery) {
        formData.append(field, this.productQuery[field]);
      }
      this.$refs.productRefFrom.validate((isValid) => {
        if (isValid) {
          if (this.productQuery.id > 0) { /*编辑*/
            doPut("/api/product", formData).then(resp => {
              if (resp.data.code === 200) {
                messageTip("编辑成功", "success");
                //页面刷新
                this.reload();
              } else {
                messageTip("编辑失败", "error");
              }
            })
          } else { /*新增*/
            doPost("/api/product", formData).then(resp => {
              if (resp.data.code === 200) {
                messageTip("提交成功", "success");
                //页面刷新
                this.reload();
              } else {
                messageTip("提交失败", "error");
              }
            })
          }
        }
      })
    },

    //删除用户
    del(id) {
      messageConfirm("您确定要删除该数据吗？").then(() => {//用户点击“确定”按钮就会触发then函数
        doDelete("/api/product/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除成功", "success");
            //页面刷新
            this.reload();
          } else {
            messageTip("删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => {//用户点击“取消”按钮就会触发catch函数
        messageTip("取消删除", "warning");
      })
    },

    //批量删除用户
    batchDel(){
      if (this.productIdArray.length <= 0){
        //提示一下
        messageTip("请选择要删除的数据", "warning");
        return;
      }
      messageConfirm("您确定要删除这些数据吗？").then(() => {//用户点击“确定”按钮就会触发then函数
        //原来是数组：[1,3,5,7] --> ids = "1,3,5,7";
        let ids = this.productIdArray.join(",");
        doDelete("/api/product", {ids: ids}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            //页面刷新
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        })
      }).catch(() => {//用户点击“取消”按钮就会触发catch函数
        messageTip("取消批量删除", "warning");
      })
    },

    //搜索
    onSearch(){
      this.getData(1);
    },

    //搜索条件重重（清空）
    onReset(){
      this.productQuery = {};
      //页面刷新
      this.reload();
    },


  }

}


</script>

<style scoped>
/*.el-table{
  margin-top: 15px;
}

.el-pagination{
  margin-top: 15px;
}*/

.form-container {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.table-container {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-top: 20px;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
  border-radius: 4px;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button--primary.is-plain {
  color: #409EFF;
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

.el-button--primary.is-plain:hover {
  color: #66b1ff;
  background-color: #c6e2ff;
  border-color: #a0cfff;
}

.el-table {
  font-size: 14px;
  line-height: 1.5;
}

.el-table th {
  background-color: #f5f7fa;
}

</style>